package com.example.asa;
import java.sql.*;

public class MySQLDatabaseConnector {
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/dagangzhuzhou";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            throw new SQLException("MySQL JDBC Driver not found", e);
        }
    }

    // 验证用户登录
    public static boolean validateUser(String username, String password) {
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);
            stmt.setString(2, password);

            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                // 账号和密码都匹配
                System.out.println("登录成功: 用户名和密码均匹配");
                return true;
            } else {
                System.out.println("登录失败: 用户名或密码错误");
                return false;
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("数据库查询出错: " + e.getMessage());
            return false;
        }
    }




    // 关闭连接资源
    public static void closeResources(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}